package integration.service.impl;

import integration.dom.Message;
import integration.properties.protocol.Protocol;
import integration.properties.protocol.ProtocolFactory;
import integration.service.MessageService;
import integration.util.MessageUtil;

public class MessageServiceImpl implements MessageService {

    @Override
    public void processMessage(final String sourceLocation, final String targetLocation) {
        if (sourceLocation == null) throw new IllegalArgumentException("Source location string cannot be null");
        if (targetLocation == null) throw new IllegalArgumentException("Target location string cannot be null");

        Message fetchedMessage = fetchMessage(sourceLocation);
        Message uncompressedMessage = MessageUtil.uncompress(fetchedMessage);

        String requestedFormat = parseFormat(targetLocation);
        String requestedCompression = parseCompression(targetLocation);
        String requestedTargetProtocol = parseProtocol(targetLocation);

        Message formattedMessage = MessageUtil.format(uncompressedMessage, requestedFormat);
        Message compressedAndFormattedMessage = MessageUtil.compress(formattedMessage, requestedCompression);

        Protocol protocol = ProtocolFactory.createProtocol(requestedTargetProtocol);
        protocol.sendMessage(compressedAndFormattedMessage, targetLocation);
    }

    private Message fetchMessage(String sourceLocation) {
        String RequestedSourceProtocol = parseProtocol(sourceLocation);
        Protocol sourceProtocol = ProtocolFactory.createProtocol(RequestedSourceProtocol);
        return sourceProtocol.fetchMessage(sourceLocation);
    }

    //visibility lifted for testing
    String parseCompression(String targetLocation) {
        String[] messageInfo = getMessageInfo(targetLocation);
        return messageInfo[messageInfo.length - 1];
    }

    //visibility lifted for testing
    String parseFormat(String targetLocation) {
        String[] messageInfo = getMessageInfo(targetLocation);
        return messageInfo[messageInfo.length - 2];
    }

    //visibility lifted for testing
    String parseProtocol(String location) {
        if (location == null) throw new IllegalArgumentException("Location string cannot be null");
        String[] split = location.split(":");
        return split[0];
    }

    private String[] getMessageInfo(String targetLocation) {
        if (targetLocation == null) throw new IllegalArgumentException("Location string cannot be null");
        String[] split = targetLocation.split("/");
        String s = split[split.length - 1];
        return s.split("\\.");
    }


}
